package com.kunbo.cn.controller.uflo;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.bstek.uflo.command.impl.jump.JumpNode;
import com.bstek.uflo.console.handler.impl.PageData;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.HistoryProcessInstance;
import com.bstek.uflo.model.HistoryTask;
import com.bstek.uflo.model.ProcessDefinition;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.model.task.Task;
import com.bstek.uflo.model.task.TaskParticipator;
import com.bstek.uflo.model.task.TaskState;
import com.bstek.uflo.process.assign.Assignee;
import com.bstek.uflo.process.flow.SequenceFlowImpl;
import com.bstek.uflo.process.node.Node;
import com.bstek.uflo.process.node.TaskNode;
import com.bstek.uflo.query.HistoryProcessInstanceQuery;
import com.bstek.uflo.query.HistoryTaskQuery;
import com.bstek.uflo.query.ProcessInstanceQuery;
import com.bstek.uflo.query.ProcessQuery;
import com.bstek.uflo.query.TaskQuery;
import com.bstek.uflo.service.HistoryService;
import com.bstek.uflo.service.ProcessService;
import com.bstek.uflo.service.StartProcessInfo;
import com.bstek.uflo.service.TaskOpinion;
import com.bstek.uflo.service.TaskService;
import com.bstek.uflo.utils.EnvironmentUtils;
import com.kunbo.cn.entity.EasyUiDataGrid2;
import com.kunbo.cn.entity.system.user.User;
import com.kunbo.cn.entity.uflo.beans.EasyUiDataGrid3;
import com.kunbo.cn.entity.uflo.entity.Tips;
import com.kunbo.cn.service.system.user.UserService;
import com.kunbo.cn.service.uflo.TipsService;
import com.kunbo.cn.util.json.JsonResult;
import com.kunbo.cn.util.retu.ReturnBean;


@RestController
@RequestMapping("flow")
public class UfloController {
		
	
		@Autowired
		private ProcessService processService;
		
		@Autowired
		private HistoryService historyService;
		
		@Autowired
		private TaskService taskService;
		
		@Autowired
	    public TipsService tipsService;
		
		@Autowired
		private UserService userService;
		
		SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		@Autowired
		private JdbcTemplate jdbc;
		/**
		 * 跳转到流程管理页面
		 * @return
		 * @author liuyu
		 */
		@GetMapping("manager")
		public ModelAndView flowManager() {
			ModelAndView mv = new ModelAndView();
			mv.setViewName("redirect:/uflo/central");
			return mv;
		}
		
		/**
		 * 跳转到流程编辑器页面
		 * @return
		 * @author liuyu
		 */
		@GetMapping("designer")
		public ModelAndView flowDesigner() {
			ModelAndView mv = new ModelAndView();
			mv.setViewName("redirect:/uflo/designer");
			return mv;
		}
		/**
		 * 查询未开启流程开始环节后第一个节点的待办人列表，返回参数均为字符串（人名）
		 * @param request
		 * @param response
		 * @return
		 */
		@PostMapping("getUsers")
		public List<String> users(HttpServletRequest request,HttpServletResponse response){
			List<String> list = new ArrayList<String>();
			String modelName = request.getParameter("key");
			ProcessDefinition d = processService.getProcessByName(modelName);
			List<Node> nd = d.getNodes();
			TaskNode node = (TaskNode) nd.get(1);
			List<Assignee> i = node.getAssignees();
			for(Assignee a:i) {
				list.add(a.getName());
			}
			return list;
		}
		/**
		 * 由表单启动一个任务,默认发起人为当前环节办理人
		 * @param modelName 模型名称，自动查询模型最新版本开启
		 * @param uuid 业务id（表单id）
		 * @param variable （流程变量）json形式回传，任意长度，统一包装成1:[{2:2},{3:3},{4:4}]形式使用
		 * @param completeNow 是否立即完成任务
		 * @param userName 指定经办人，可不传
		 * @param request
		 * @param response
		 * @return
		 * @author liuyu
		 */
		//由表单启动一个任务
		@PostMapping("startProcessWithForm")
		public JsonResult startProcess(String modelName,String uuid,String variable,boolean completeNow,String userName,HttpServletRequest request,HttpServletResponse response) {
			JsonResult result = new JsonResult();
			System.out.println(modelName+"模板名称为=====99999");
			//User user = ((User)session.getAttribute("user"));
			//System.out.println(user+"====");
			User user = (User)request.getSession().getAttribute("user");
			StartProcessInfo startProcessInfo = new StartProcessInfo(user.getName());
			startProcessInfo.setBusinessId(uuid);
			Map<String,Object> variableMaps=buildVariables(variable);
			if(variableMaps!=null){
				startProcessInfo.setVariables(variableMaps);
			}
			if(!completeNow) 
				startProcessInfo.setCompleteStartTask(completeNow);
			else
				startProcessInfo.setCompleteStartTask(true);
			try {
				ProcessInstance process = processService.startProcessByName(modelName,startProcessInfo);
				if(!"".equals(userName)&&null!=userName) {
					long rootId = process.getRootId();
					String taskName = process.getCurrentTask();
					TaskQuery query=taskService.createTaskQuery();
					query.rootProcessInstanceId(rootId);
					List<Task> task = query.nameLike(taskName).list();
					if(task.size()==1) {
						checkAssignee(task.get(0).getId(),task.get(0).getNodeName(),userName);
					}
				}
				result.setObj(process);
				result.setMsg("流程发起成功");
				result.setStatus("0");
			}catch(Exception e) {
				e.printStackTrace();
			}
			return result;
		}
		/**
		 * 办理任务
		 * @param url
		 * @return
		 * @author liuyu
		 */
		@GetMapping("approve")
		public ModelAndView approveTask(String url,String taskId) {
			//System.out.println(url+"打开表单页面");
			System.out.println("加载页面的路径为："+url);
			ModelAndView mv = new ModelAndView();
			mv.addObject("url", url);
			mv.addObject("taskId", taskId);
			mv.setViewName("activiti/Uflo/showFormUflo");
			return mv;
		}
		/**
		 * 查看任务详情
		 * @param url
		 * @return
		 * @author liuyu
		 */
		@GetMapping("readonly")
		public ModelAndView readonly(String url,String taskId) {
			ModelAndView mv = new ModelAndView();
			mv.addObject("url", url);
			mv.addObject("taskId", taskId);
			mv.setViewName("activiti/Uflo/showFormUfloReadOnly");
			return mv;
		}
		/**
		 * 当前用户认领任务
		 * @param req
		 * @param resp
		 * @return
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		//领取任务
		@PostMapping("claimTask")
		public JsonResult claimTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			JsonResult result = new JsonResult();
			String loginUsername=EnvironmentUtils.getEnvironment().getLoginUser();
			String taskId=req.getParameter("taskId");
			taskService.claim(Long.valueOf(taskId), loginUsername);
			result.setStatus("0");
			result.setMsg("任务领取成功");
			return result;
		}
		/**
		 * 跳转待办任务页面
		 * @return
		 * @author liuyu
		 */
		@GetMapping("toTodoTask")
		public ModelAndView toTodoTask() {
			ModelAndView mv = new ModelAndView();
			mv.setViewName("activiti/Uflo/FlowManager");
			return mv;
		}
		/**
		 * 
		 * <p>Title: getTaskCount</p>
		 * <p>Description:获取当前用户待办任务总数 </p>
		 * @param req
		 * @param resp
		 * @return
		 * @throws ServletException
		 * @throws IOException
		 */
		@GetMapping("getTaskCount")
		public String getTaskCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			String loginUsername=EnvironmentUtils.getEnvironment().getLoginUser();
			TaskQuery query=taskService.createTaskQuery();
			query.addTaskState(TaskState.Created);
			query.addTaskState(TaskState.InProgress);
			query.addTaskState(TaskState.Ready);
			query.addTaskState(TaskState.Suspended);
			query.addTaskState(TaskState.Reserved);
			query.addAssignee(loginUsername).addOrderDesc("createDate");
			Integer count = query.count();
			return Integer.toString(count);
			
		}
		
		/**
		 * 获取待办任务列表
		 * @param req
		 * @param resp
		 * @return
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		@GetMapping("loadTodo")
		public EasyUiDataGrid2 loadTodo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			String loginUsername=EnvironmentUtils.getEnvironment().getLoginUser();
			String taskName=req.getParameter("taskName");
			String tName=req.getParameter("tName");
			String _page = req.getParameter("page");
			String _rows = req.getParameter("rows");
			int page = Integer.parseInt(_page);
			int rows = Integer.parseInt(_rows);
			int firstResult=(page-1)*rows;
			int total=0;
			//System.out.println(req.getSession().getMaxInactiveInterval()+"超期时长！！！！！！！！！！！！！！");
			List<Task> tasks = null;
			List<Map<String,String>> list = new ArrayList<Map<String,String>>();
			TaskQuery query=taskService.createTaskQuery();
			query.addTaskState(TaskState.Created);
			query.addTaskState(TaskState.InProgress);
			query.addTaskState(TaskState.Ready);
			query.addTaskState(TaskState.Suspended);
			query.addTaskState(TaskState.Reserved);
			if(!"".equals(tName)&&null!=tName) {
				Tips tip = tipsService.findByTName(tName);
				if(null!=tip) {
					query.rootProcessInstanceId(Long.valueOf(tip.getProcInsId()));
					query.addAssignee(loginUsername).addOrderDesc("createDate").page(firstResult, rows);
					if(StringUtils.isNotBlank(taskName))
						query.nameLike("%"+taskName+"%");
				}else 
					return new EasyUiDataGrid2(total, list);
				
			}else {
				query.addAssignee(loginUsername).addOrderDesc("createDate").page(firstResult, rows);
				if(StringUtils.isNotBlank(taskName))
					query.nameLike("%"+taskName+"%");
			}
			query.count();
			tasks=query.list();
			for(Task t:tasks) {
				Map<String,String> map = new HashMap<String,String>();
				//System.out.println(t.getRootProcessInstanceId());
				HistoryTaskQuery his = historyService.createHistoryTaskQuery().rootProcessInstanceId(t.getRootProcessInstanceId()).addOrderAsc("createDate");
				List<HistoryTask> h = his.list();
				Tips tp = tipsService.selectByProcInsId(String.valueOf(t.getRootProcessInstanceId()));
				if(null!=tp) 
				map.put("tips", tp.getTName());
				User user = userService.findByName(t.getAssignee());
				User crateUser = userService.findByName(h.get(0).getOwner());
				//获取节点类型
				ProcessDefinition pd = processService.getProcessById(t.getProcessId());
				map.put("firBusinessId", h.get(0).getBusinessId());
				map.put("firUrl", h.get(0).getUrl());
				map.put("taskName", t.getTaskName());
				map.put("title", pd.getName());
				map.put("id", String.valueOf(t.getId()));
				map.put("assignee", user.getActual_name());
				map.put("progress", String.valueOf(t.getProgress()));
				map.put("state", String.valueOf(t.getState()));
				map.put("own", t.getOwner());
				map.put("description", t.getDescription());
				map.put("businessId", t.getBusinessId());
				map.put("processInstanceId", String.valueOf(t.getProcessInstanceId()));
				map.put("createDate", formatDate(t.getCreateDate()));
				map.put("ulfoCreateDate", formatDate(h.get(0).getCreateDate()));//流程创建时间
				map.put("cretePerson", crateUser.getActual_name());//发起人
				map.put("prevTask", t.getPrevTask());
				map.put("url", t.getUrl());
				Node node = pd.getNode(t.getNodeName());
				List<SequenceFlowImpl> nodes=node.getSequenceFlows();
				if(nodes!=null&&nodes.size()==1){
					for(SequenceFlowImpl flow:nodes){
						String flowName=flow.getToNode();
						if(flowName!=null && !flowName.startsWith(TaskService.TEMP_FLOW_NAME_PREFIX)){
							Node n = pd.getNode(flow.getToNode());
							map.put("nodeType", n.getType().name());
							map.put("nextNode", flowName);
						}
					}
				}
				list.add(map);
			}
			return new EasyUiDataGrid2(total, list);
		}
		/**
		 * 跳转待领取任务页面
		 * @return
		 * @author liuyu
		 */
		@GetMapping("toClaimTask")
		public ModelAndView toClaimTask() {
			ModelAndView mv = new ModelAndView();
			mv.setViewName("activiti/Uflo/claimFlowManager");
			return mv;
		}
		/**
		 * 待领取任务
		 * @param req
		 * @param resp
		 * @return
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		@GetMapping("loadClaim")
		public EasyUiDataGrid2 loadClaim(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			String loginUsername=EnvironmentUtils.getEnvironment().getLoginUser();
			String _page = req.getParameter("page");
			String _rows = req.getParameter("rows");
			int page = Integer.parseInt(_page);
			int rows = Integer.parseInt(_rows);
			int firstResult=(page-1)*rows;
			String taskName=req.getParameter("taskName");
			String tName=req.getParameter("tName");
			int total=0;
			List<Task> tasks = null;
			List<Map<String,String>> list = new ArrayList<Map<String,String>>();
			TaskQuery query=taskService.createTaskQuery();
			if(!"".equals(tName)&&null!=tName) {
				Tips tip = tipsService.findByTName(tName);
				if(null!=tip) {
					query.rootProcessInstanceId(Long.valueOf(tip.getProcInsId()));
					if(StringUtils.isNotBlank(taskName))
						query.nameLike("%"+taskName+"%");
					query.addTaskState(TaskState.Ready).addParticipator(loginUsername).addOrderDesc("createDate").page(firstResult, rows);
				}else 
					return new EasyUiDataGrid2(total, list);
			}else {
				if(StringUtils.isNotBlank(taskName))
					query.nameLike("%"+taskName+"%");
				query.addTaskState(TaskState.Ready).addParticipator(loginUsername).addOrderDesc("createDate").page(firstResult, rows);
			}
			total=query.count();
			tasks=query.list();
			for(Task t:tasks) {
				Map<String,String> map = new HashMap<String,String>();
				HistoryTaskQuery his = historyService.createHistoryTaskQuery().rootProcessInstanceId(t.getRootProcessInstanceId()).addOrderAsc("createDate");
				List<HistoryTask> h = his.list();
				Tips tp = tipsService.selectByProcInsId(String.valueOf(t.getRootProcessInstanceId()));
				if(null!=tp) 
					map.put("tips", tp.getTName());
				map.put("firBusinessId", h.get(0).getBusinessId());
				map.put("firUrl", h.get(0).getUrl());
				map.put("taskName", t.getTaskName());
				map.put("id", String.valueOf(t.getId()));
				map.put("assignee", t.getAssignee());
				map.put("progress", String.valueOf(t.getProgress()));
				map.put("state", String.valueOf(t.getState()));
				map.put("own", t.getOwner());
				map.put("description", t.getDescription());
				map.put("businessId", t.getBusinessId());
				map.put("processInstanceId", String.valueOf(t.getProcessInstanceId()));
				map.put("createDate", formatDate(t.getCreateDate()));
				map.put("ulfoCreateDate", formatDate(h.get(0).getCreateDate()));//流程创建时间
				map.put("cretePerson", h.get(0).getOwner());//发起人
				map.put("prevTask", t.getPrevTask());
				map.put("url", t.getUrl());
				list.add(map);
				
			}
			return new EasyUiDataGrid2(total, list);
		}
		
		
		/**
		 * 跳转历史任务页面
		 * @return
		 * @author liuyu
		 */
		@GetMapping("toHisToryTasks")
		public ModelAndView toHisToryTasks() {
			ModelAndView mv = new ModelAndView();
			mv.setViewName("activiti/Uflo/ownFlowhis");
			return mv;
		}
		
		/**
		 * 获取历史任务
		 * @param req
		 * @param resp
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		@GetMapping("loadHistoryTasks")
		public EasyUiDataGrid2 loadHistoryTasks(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			String loginUsername=EnvironmentUtils.getEnvironment().getLoginUser();
			String _page = req.getParameter("page");
			String _rows = req.getParameter("rows");
			String taskName = req.getParameter("taskName");
			int page = Integer.parseInt(_page);
			int rows = Integer.parseInt(_rows);
			int firstResult=(page-1)*rows;
			HistoryTaskQuery historyTaskQuery = historyService.createHistoryTaskQuery().assignee(loginUsername);
			if(StringUtils.isBlank(taskName)) {
				historyTaskQuery.addOrderDesc("endDate").page(firstResult, rows);
			}else {
				historyTaskQuery.assignee(loginUsername).nameLike(taskName).addOrderDesc("endDate").page(firstResult, rows);
			}
			int total=historyTaskQuery.count();
			List<HistoryTask> hisTask=historyTaskQuery.list();
			List<Map<String,String>> list = new ArrayList<Map<String,String>>();
			for(HistoryTask t:hisTask) {
				Map<String,String> map = new HashMap<String,String>();
				HistoryTaskQuery his = historyService.createHistoryTaskQuery().rootProcessInstanceId(t.getRootProcessInstanceId()).addOrderAsc("createDate");
				List<HistoryTask> h = his.list();
				User user = userService.findByName(t.getAssignee());
				User crateUser = userService.findByName(h.get(0).getOwner());
				ProcessDefinition pd = processService.getProcessById(t.getProcessId());
				map.put("title", pd.getName());
				map.put("firBusinessId", h.get(0).getBusinessId());
				map.put("firUrl", h.get(0).getUrl());
				map.put("taskName", t.getTaskName());
				map.put("id", String.valueOf(t.getId()));
				map.put("taskId", String.valueOf(t.getTaskId()));
				map.put("assignee", user.getActual_name());
				map.put("state", String.valueOf(t.getState()));
				map.put("own", t.getOwner());
				map.put("description", t.getDescription());
				map.put("businessId", t.getBusinessId());
				map.put("processInstanceId", String.valueOf(t.getProcessInstanceId()));
				map.put("createDate", formatDate(t.getCreateDate()));
				map.put("ulfoCreateDate", formatDate(h.get(0).getCreateDate()));//流程创建时间
				map.put("cretePerson", crateUser.getActual_name());//发起人
				map.put("url", t.getUrl());
				map.put("nodeName", t.getNodeName());
				map.put("opinion", t.getOpinion());
				map.put("dueDate", formatDate(t.getDuedate()));
				list.add(map);
			}
			return new EasyUiDataGrid2(total, list);
		}
		
		/**
		 * 跳转连接线列表
		 * @param taskId
		 * @return
		 */
		@GetMapping("toFlows")
		public ModelAndView toFlows(String taskId) {
			ModelAndView mv = new ModelAndView();
			mv.addObject("taskId", taskId);
			mv.setViewName("activiti/Uflo/flows");
			return mv;
		}
		/**
		 * 获取当前任务分流出的连接线
		 * @param.] req
		 * @param resp
		 * @return
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		@PostMapping("loadSequenceFlows")
		public List<SequenceFlowImpl> loadSequenceFlows(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			long taskId=Long.valueOf(req.getParameter("taskId"));
			Task task = taskService.getTask(taskId);
			ProcessDefinition pd = processService.getProcessById(task.getProcessId());
			Node node = pd.getNode(task.getNodeName());
			List<SequenceFlowImpl> flows=new ArrayList<SequenceFlowImpl>();
			List<SequenceFlowImpl> list=node.getSequenceFlows();
			if(list!=null){
				for(SequenceFlowImpl flow:list){
					String flowName=flow.getName();
//					if(flowName!=null && !flowName.startsWith(TaskService.TEMP_FLOW_NAME_PREFIX)){
//						flows.add(flow);
//					}
					//连线的名称可能为空，所以在这无需判断，只要能显示节点
//					if(!flowName.startsWith(TaskService.TEMP_FLOW_NAME_PREFIX)){
//						
//					}
					flows.add(flow);
				}
			}
			return flows;
		}
		
		/**
		 * 跳转分支节点连接线列表
		 * @param taskId
		 * @return
		 */
		@GetMapping("toForkFlows")
		public ModelAndView toForkFlows(@RequestParam("taskId")String taskId,@RequestParam("nextNode")String nextNode) {
			ModelAndView mv = new ModelAndView();
			mv.addObject("taskId", taskId);
			mv.addObject("nextNode", nextNode);
			mv.setViewName("activiti/Uflo/forkTaskNodes");
			return mv;
		}
		/**
		 * 获取下一个节点任务分流出的连接线(仅用于分支节点)
		 * @param req
		 * @param resp
		 * @return
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		@PostMapping("loadNextNodeSequenceFlows")
		public List<Map<String,String>> loadNextNodeSequenceFlows(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			long taskId=Long.valueOf(req.getParameter("taskId"));
			String nextNode=req.getParameter("nextNode");
			Task task = taskService.getTask(taskId);
			ProcessDefinition pd = processService.getProcessById(task.getProcessId());
			Node node = pd.getNode(nextNode);
			List<Map<String,String>> flows=new ArrayList<Map<String,String>>();
			List<SequenceFlowImpl> list=node.getSequenceFlows();
			if(list!=null){
				for(SequenceFlowImpl flow:list){
					String flowName=flow.getName();
					if(flowName!=null && !flowName.startsWith(TaskService.TEMP_FLOW_NAME_PREFIX)){
						Map<String,String> map = new HashMap<String,String>();
						map.put("name", flow.getName());
						map.put("toNode", flow.getToNode());
						map.put("expression", flow.getExpression());
						flows.add(map);
					}
				}
			}
			return flows;
		}
		/**
		 * 下一步节点选择页面
		 * @param taskId
		 * @return
		 * @author liuyu
		 */
		@GetMapping("toNode")
		public ModelAndView toNode(String taskId) {
			ModelAndView mv = new ModelAndView();
			mv.addObject("taskId", taskId);
			mv.setViewName("activiti/Uflo/node");
			return mv;
		}
		
		/**
		 * 获取下一步节点
		 * @param req
		 * @param resp
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		@PostMapping("loadNode")
		public List<Map<String,String>> loadNode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			long taskId=Long.valueOf(req.getParameter("taskId"));
			Task task = taskService.getTask(taskId);
			ProcessDefinition pd = processService.getProcessById(task.getProcessId());
			Node node = pd.getNode(task.getNodeName());
			List<Map<String,String>> flows=new ArrayList<Map<String,String>>();
			List<SequenceFlowImpl> list=node.getSequenceFlows();
			if(list!=null){
				for(SequenceFlowImpl flow:list){
					String flowName=flow.getToNode();
					if(flowName!=null && !flowName.startsWith(TaskService.TEMP_FLOW_NAME_PREFIX)){
						Map<String,String> map = new HashMap<String,String>();
						map.put("text", flow.getToNode());
						flows.add(map);
					}
				}
			}
			return flows;
		}
		
		/**
		 * 获取可跳转节点列表
		 * @param req
		 * @param resp
		 * @return
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		@PostMapping("loadJumpTasks")
		public List<JumpNode> loadJumpTasks(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			long taskId=Long.valueOf(req.getParameter("taskId"));
			List<JumpNode> nodes=taskService.getAvaliableForwardTaskNodes(taskId);
			//writeObjectToJson(resp, page);(resp, nodes);
			return nodes;
		}
		/**
		 * 跳转到潜在班里人列表页面
		 * @param taskId
		 * @param taskNodeName
		 * @return
		 * @author liuyu
		 */
		@GetMapping("toNextNodeClaimUsers")
		public ModelAndView getNextNode(String taskId,String taskNodeName) {
			ModelAndView mv = new ModelAndView();
			mv.addObject("taskId", taskId);
			mv.addObject("taskNodeName", taskNodeName);
			mv.setViewName("activiti/Uflo/assignees");
			return mv;
		}
		
		/**
		 * 根据任务id和节点名称获取潜在办理人列表
		 * @param req
		 * @param resp
		 * @return
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		@PostMapping("getNextNodeClaimUsers")
		public List<Map<String,String>> getNextNodeClaimUsers(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			long taskId=Long.valueOf(req.getParameter("taskId"));
			String taskNodeName=String.valueOf(req.getParameter("taskNodeName"));
			List<Map<String,String>> list = new ArrayList<Map<String,String>>();
			if(!taskNodeName.equals("结束")) {
				List<String> claimUsers=taskService.getTaskNodeAssignees(taskId,taskNodeName);
				for(String t:claimUsers) {
					Map<String,String> map = new HashMap<String,String>();
					User u = userService.findByName(t);
					map.put("name", t);
					map.put("actual_name", u.getActual_name());
					list.add(map);
					//System.out.println("name="+t);
				}
			}
			return list;
		}
		/**
		 * 根据任务id获取潜在办理人列表（暂不使用）
		 * @param req
		 * @param resp
		 * @return
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		@PostMapping("getClaimUsers")
		public List<Map<String,String>> loadCliamUsers(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			long taskId=Long.valueOf(req.getParameter("taskId"));
			List<TaskParticipator> claimUsers=taskService.getTaskParticipators(taskId);
			List<Map<String,String>> list = new ArrayList<Map<String,String>>();
			for(TaskParticipator t:claimUsers) {
				Map<String,String> map = new HashMap<String,String>();
				map.put("name", t.getUser());
				User u = userService.findByName(t.getUser());
				map.put("acName", u.getActual_name());
				list.add(map);
			}
			return list;
		}
		
		
		/**
		 * 完成任务
		 * @param req
		 * @param resp
		 * @return
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		@PostMapping("completeTask")
		public JsonResult completeTask(Context context,HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			JsonResult result = new JsonResult();
			long taskId=Long.valueOf(req.getParameter("taskId"));//任务id
			String sequenceFlowName=req.getParameter("flowName");//连线名称
			String opinion=req.getParameter("opinion");//处理意见
			String variables=req.getParameter("variables");//变量
			String assignee=req.getParameter("userName");//下一步办理人名称
			String nodeName=req.getParameter("nodeName");//下一步节点名称
			//TODO
			Map<String,Object> variableMaps=buildVariables(variables);
			Task task = taskService.getTask(taskId);
			if(TaskState.Created.equals(task.getState())||TaskState.Reserved.equals(task.getState())) {
				taskService.start(taskId);
			}
			TaskOpinion op = new TaskOpinion(opinion);
			if(variableMaps!=null&&!StringUtils.isBlank(sequenceFlowName)) {
				checkAssignee(taskId,nodeName,assignee);
				taskService.complete(taskId,sequenceFlowName,variableMaps,op);	
				result.setMsg("任务办理成功");
				result.setStatus("0");
			}else if(variableMaps!=null&&StringUtils.isBlank(sequenceFlowName)) {
				taskService.complete(taskId, variableMaps,op);
				result.setMsg("任务办理成功");
				result.setStatus("0");
			}else if(variableMaps==null&&!StringUtils.isBlank(sequenceFlowName)) {
				checkAssignee(taskId,nodeName,assignee);
				taskService.complete(taskId,sequenceFlowName,op);
				result.setMsg("任务办理成功");
				result.setStatus("0");
			}else{
				taskService.complete(taskId, op);
				//System.out.println("未指定流向");
				result.setMsg("任务办理成功");
				result.setStatus("0");
			}
			return result;
		}
		
		/**
		 * 包装变量实体
		 * @param variables
		 * @return
		 * @author liuyu
		 */
		private Map<String,Object> buildVariables(String variables){
			if(StringUtils.isBlank(variables)){
				return null;
			}
			ObjectMapper mapper=new ObjectMapper();
			try {
				@SuppressWarnings("unchecked")
				List<Map<String,Object>> list=mapper.readValue(variables, ArrayList.class);
				Map<String,Object> map=new HashMap<String,Object>();
				for(Map<String,Object> m:list){
					String key=m.get("key").toString();
					Object value=m.get("value");
					map.put(key, value);
				}
				return map;
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		
		/**
		 * 根据uuid取出相关联流程任务的批注信息，并以时间排序
		 * @param taskId
		 * @return
		 * @author liuyu
		 */
		@PostMapping("getOpinionsByUuid")
		public JsonResult getOpinionsByUuid(String uuid) {
			JsonResult result = new JsonResult();
			List<HistoryTask> hisTask = historyService.createHistoryTaskQuery().businessId(uuid).addOrderAsc("createDate").list();
			List<Map<String,String>> list = new ArrayList<Map<String,String>>();
			for(HistoryTask t:hisTask) {
				Map<String,String> map = new HashMap<String,String>();
				TaskState state = t.getState();
				map.put("endDate", formatDate(t.getEndDate()));
				map.put("assignee", t.getAssignee());
				map.put("taskName", t.getTaskName());
				map.put("opinion", t.getOpinion());
				map.put("state", state.name());
				list.add(map);
			}
			result.setList(list);
			result.setStatus("0");
			return result;
		}
		
		
		/**
		 * 根据任务id取出相关联流程任务的批注信息，并以时间排序
		 * @param taskId
		 * @return
		 * @author liuyu
		 */
		@PostMapping("getOpinions")
		public JsonResult getOpinions(String taskId) {
			JsonResult result = new JsonResult();
			HistoryTask his = historyService.getHistoryTask(Long.valueOf(taskId));
			List<HistoryTask> hisTask = null;
			HistoryTaskQuery h =  historyService.createHistoryTaskQuery();
			if(null!=his) {
				hisTask = h.rootProcessInstanceId(his.getRootProcessInstanceId()).addOrderAsc("createDate").list();
			}
			if(null==hisTask||hisTask.size()<1) {
				Task task = taskService.getTask(Long.valueOf(taskId));
				hisTask = h.rootProcessInstanceId(task.getRootProcessInstanceId()).addOrderAsc("createDate").list();
			}
			List<Map<String,String>> list = new ArrayList<Map<String,String>>();
			for(HistoryTask t:hisTask) {
				Map<String,String> map = new HashMap<String,String>();
				TaskState state = t.getState();
				map.put("endDate", formatDate(t.getEndDate()));
				map.put("assignee", t.getAssignee());
				map.put("taskName", t.getTaskName());
				map.put("opinion", t.getOpinion());
				map.put("state", state.name());
				list.add(map);
			}
			result.setList(list);
			result.setStatus("0");
			return result;
		}
		
		@PostMapping("getOpinionsForDatagrid")
		public EasyUiDataGrid3 getOpinionsForDatagrid(String taskId) {
			EasyUiDataGrid3 result = new EasyUiDataGrid3();
			HistoryTask his = historyService.getHistoryTask(Long.valueOf(taskId));
			List<HistoryTask> hisTask = null;
			HistoryTaskQuery h =  historyService.createHistoryTaskQuery();
			if(null!=his) {
				hisTask = h.rootProcessInstanceId(his.getRootProcessInstanceId()).addOrderAsc("createDate").list();
			}
			if(null==hisTask||hisTask.size()<1) {
				Task task = taskService.getTask(Long.valueOf(taskId));
				hisTask = h.rootProcessInstanceId(task.getRootProcessInstanceId()).addOrderAsc("createDate").list();
			}
			List<Map<String,String>> list = new ArrayList<Map<String,String>>();
			for(HistoryTask t:hisTask) {
				Map<String,String> map = new HashMap<String,String>();
				TaskState state = t.getState();
				map.put("endDate", formatDate(t.getEndDate()));
				map.put("assignee", t.getAssignee());
				map.put("taskName", t.getTaskName());
				map.put("opinion", t.getOpinion());
				map.put("state", state.name());
				list.add(map);
			}
			result.setRows(list);
			result.setTotal(list.size());
			return result;
		}
		
		/**
		 * 根据任务id判断是否可以回退到上一个节点
		 * @param taskId
		 * @return
		 * @author liuyu
		 */
		@PostMapping("canWithDraw")
		public JsonResult canWithDraw(Long taskId) {
			JsonResult result = new JsonResult();
			boolean can= taskService.canWithdraw(taskId);
			result.setObj(can);
			result.setStatus("0");
			return result;
		}
		/**
		 * 驳回并批注
		 * @param taskId 任务id
		 * @param opinion 批注信息
		 * @return
		 * @author liuyu
		 */
		@PostMapping("withDrwa")
		public JsonResult withDraw(Long taskId,String opinion) {
			JsonResult result = new JsonResult();
			TaskOpinion op = new TaskOpinion(opinion);
			taskService.withdraw(taskId,op);
			result.setMsg("驳回成功");
			result.setStatus("0");
			return result;
		}
//		@PostMapping("getDeployed")
//		public List<Map<String,String>> getDeployed() {
//			List<ProcessDefinition> pd = processService.createProcessQuery().list();
//			List<Map<String,String>> list = new ArrayList<Map<String,String>>();
//			for(ProcessDefinition p : pd) {
//				Map<String,String> map = new HashMap<String,String>();
//				map.put("key", p.getKey());
//				map.put("name", p.getName());
//				list.add(map);
//			}
//			return list;
//		}
		
		@PostMapping("getDeployed")
		public List<Map<String,Object>> getDeployed() {
			String sql = "select id_  id,name_ name from uflo_process GROUP BY name_";
			List<Map<String,Object>> list = jdbc.queryForList(sql);
			return list;
		}
		
		
		/**
		 * 获取任务状态
		 * @param uuid
		 * @return 0任务进行中，msg当前任务执行环节 。1：不成功，msg未找到对应表单数据。2：当前任务已完成，msg任务已完成
		 */
		@PostMapping("getStats")
		public JsonResult getStats(String uuid) {
			JsonResult result = new JsonResult();
			//查询form表中关联的taskId
			List<Task> task = taskService.createTaskQuery().businessId(uuid).addOrderAsc("createDate").list();
			List<HistoryTask> hisTask = historyService.createHistoryTaskQuery().businessId(uuid).addOrderAsc("createDate").list();
			if(null==task||task.size()<1) {
				if(null==hisTask||hisTask.size()<1) {
					result.setStatus("1");
					result.setMsg("未开启");
					return result;
				}else {
					result.setStatus("2");
					result.setMsg("已完成");
					return result;
				}
			}else {
				String name = task.get(task.size()-1).getTaskName();
				result.setStatus("0");
				result.setMsg(name);
				return result;
			}
		}
		/**
		 * 跳转已部署的流程
		 * @return
		 */
		@GetMapping("getProcess")
		public ModelAndView getProcessInstanceList() {
			ModelAndView mv = new ModelAndView();
			mv.setViewName("/activiti/Uflo/processInstanceList");
			return mv;
		}
		/**
		 * 获取进度
		 * @param req
		 * @param resp
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		@GetMapping("loadProcess")
		public EasyUiDataGrid2 loadProcess(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			String name=req.getParameter("name");
			String _page = req.getParameter("page");
			String _rows = req.getParameter("rows");
			int page = Integer.parseInt(_page);
			int rows = Integer.parseInt(_rows);
			int firstResult=(page-1)*rows;
			ProcessQuery query = processService.createProcessQuery();
			query.page(firstResult, rows);
			query.addOrderDesc("createDate");
			if(StringUtils.isNotBlank(name)){
				query.nameLike("%"+name+"%");
			}
			int total=query.count();
			List<ProcessDefinition> processes=query.list();
			return new EasyUiDataGrid2(total,processes);//////writeObjectToJson(resp, page);(resp, page);
		}
		/**
		 * 通过按钮启动任务
		 */
		@GetMapping("startWithButton")
		public ModelAndView setVariables() {
			ModelAndView mv = new ModelAndView();
			mv.setViewName("activiti/Uflo/startWithButton");
			return mv;
		}
		/**
		 * 获取历史流程实例列表
		 * @param req
		 * @param resp
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		@GetMapping("loadHistoryProcessInstance")
		public EasyUiDataGrid2 loadHistoryProcessInstance(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			String _page = req.getParameter("page");
			String _rows = req.getParameter("rows");
			int page = Integer.parseInt(_page);
			int rows = Integer.parseInt(_rows);
			int firstResult=(page-1)*rows;
			int total=0;
			HistoryProcessInstanceQuery historyProcessInstanceQuery = historyService.createHistoryProcessInstanceQuery();
			historyProcessInstanceQuery.addOrderDesc("createDate");
			historyProcessInstanceQuery.page(firstResult, rows);
			total=historyProcessInstanceQuery.count();
			List<HistoryProcessInstance> list=historyProcessInstanceQuery.list();
			return new EasyUiDataGrid2(total, list);
		}
		
		/**
		 * 检查指定的执行人是否为空，不为空则执行对应的判断，并指定下一步节点的执行人
		 * @param taskId
		 * @param nodeName
		 * @param assignee
		 * @author liuyu
		 */
		private void checkAssignee(long taskId,String nodeName,String assignee) {
			if(StringUtils.isNotBlank(assignee)) {
				String[] assignees = assignee.split(",");
				if(assignees.length>1) {
					taskService.saveTaskAppointor(taskId, assignees, nodeName);
				}else {
					taskService.saveTaskAppointor(taskId, assignee, nodeName);
				}
			}
		}
		/**
		 * 格式化日期
		 * @param date
		 * @return
		 */
		private String formatDate(Date date) {
			String caleder="";
			if(null!=date) {
				caleder = simple.format(date);
				return caleder;
			}
			return caleder;
		}
		
		/**
		 * 获取历史任务列表
		 * @param req
		 * @param resp
		 * @return
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		public JsonResult loadHistory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			JsonResult result = new JsonResult();
			String loginUsername=EnvironmentUtils.getEnvironment().getLoginUser();
			int pageSize=Integer.valueOf(req.getParameter("pageSize"));
			int pageIndex=Integer.valueOf(req.getParameter("pageIndex"));
			String taskName=req.getParameter("taskName");
			int firstResult=(pageIndex-1)*pageSize;
			HistoryTaskQuery query=historyService.createHistoryTaskQuery();
			if(StringUtils.isNotBlank(taskName)){
				query.nameLike("%"+taskName+"%");
			}
			query.assignee(loginUsername).addOrderDesc("endDate").page(firstResult, pageSize);
			int total=query.count();
			List<HistoryTask> tasks=query.list();
			PageData pageData=new PageData(tasks,pageSize,pageIndex,total);
//			//writeObjectToJson(resp, page);(resp, pageData);
			return result;
		}
		
		
		
		/**
		 * 获取流程实例
		 * @param req
		 * @param resp
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		@GetMapping("loadProcessInstance")
		public EasyUiDataGrid2 loadProcessInstance(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			ProcessInstanceQuery query = processService.createProcessInstanceQuery();
//			long processId=Long.valueOf(req.getParameter("processId"));
			String _page = req.getParameter("page");
			String _rows = req.getParameter("rows");
			int page = Integer.parseInt(_page);
			int rows = Integer.parseInt(_rows);
			int firstResult=(page-1)*rows;
			query.page(firstResult, rows);
//			query.processId(processId);
			query.addOrderDesc("createDate");
			int total=query.count();
			List<ProcessInstance> list=query.list();
			return new EasyUiDataGrid2(total,list);
		}
		
		/**
		 * 跳转任务
		 * @param req
		 * @param resp
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		public void jumpTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			long taskId=Long.valueOf(req.getParameter("taskId"));
			String nodeName=req.getParameter("nodeName");
			taskService.forward(taskId, nodeName);
		}
		public void loadTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			TaskQuery query = taskService.createTaskQuery();
			query.addTaskState(TaskState.Created);
			query.addTaskState(TaskState.InProgress);
			query.addTaskState(TaskState.Ready);
			query.addTaskState(TaskState.Suspended);
			query.addTaskState(TaskState.Reserved);
			Long processInstanceId=Long.valueOf(req.getParameter("processInstanceId"));
			query.processInstanceId(processInstanceId);
			query.addOrderDesc("createDate");
			//writeObjectToJson(resp, page);(resp, query.list());
		}
		/**
		 * 通过
		 * @param req
		 * @param resp
		 * @return
		 * @throws ServletException
		 * @throws IOException
		 */
		@PostMapping("startProcess")
		public JsonResult startProcess(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			JsonResult result = new JsonResult();
			long processId=Long.valueOf(req.getParameter("processId"));
			boolean compNow=Boolean.valueOf(req.getParameter("compNow"));
			StartProcessInfo startProcessInfo = new StartProcessInfo(EnvironmentUtils.getEnvironment().getLoginUser());
			startProcessInfo.setCompleteStartTask(compNow);
			String variables=req.getParameter("variables");
			Map<String,Object> variableMaps=buildVariables(variables);
			if(variableMaps!=null){
				startProcessInfo.setVariables(variableMaps);
			}
			ProcessInstance pro = processService.startProcessById(processId, startProcessInfo);
			result.setObj(pro);
			result.setStatus("0");
			return result;
		}
		
		@PostMapping("deleteProcess/{processId}")
		public JsonResult deleteProcess(@PathVariable("processId")Long processId,HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			JsonResult result = new JsonResult();
			processService.deleteProcess(processId);
			result.setMsg("删除成功");
			result.setStatus("0");
			return result;
		}
		
		public void deleteProcessInstance(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			long processInstanceId=Long.valueOf(req.getParameter("processInstanceId"));
			processService.deleteProcessInstanceById(processInstanceId);
		}
		
		@PostMapping("getPidByUuid")
		public JsonResult getPidByUuid(String uuid) {
			JsonResult result = new JsonResult();
			List<HistoryTask> list = historyService.createHistoryTaskQuery().businessId(uuid).list();
			try {
				if(null!=list&&list.size()>0) {
					Long taskId = list.get(0).getTaskId();
					result.setObj(taskId);
					result.setMsg("获取成功");
					result.setStatus("0");
				}else {
					result.setObj(null);
					result.setMsg("fail");
					result.setStatus("1");
				}
			} catch (Exception e) {
				 
			}
			
			
			return result;
		}
		/**
		 * 判断任务办理页面选择流向按钮的显示与否接口
		 * @param uuid
		 * @return
		 */
		@RequestMapping("judge")
		public JsonResult judgeFlowDirectionTransactor (Long taskId) {
			System.out.println("当前任务id为==="+taskId);
			JsonResult result = new JsonResult();
			Task task = taskService.getTask(taskId);
			ProcessDefinition pd = processService.getProcessById(task.getProcessId());
			Node node = pd.getNode(task.getNodeName());
			List<SequenceFlowImpl> flows=new ArrayList<SequenceFlowImpl>();
			List<SequenceFlowImpl> list=node.getSequenceFlows();
			if(list!=null){
				for(SequenceFlowImpl flow:list){
					String flowName=flow.getName();
					if(flowName!=null && !flowName.startsWith(TaskService.TEMP_FLOW_NAME_PREFIX)){
						flows.add(flow);
					}
				}
			}
			if(list.size() >0 && list.size()<=1) {
				//回调一个方法，判断任务办理人是不是一个
				System.out.println(list.get(0).getName());
				if(getTaskTransactor(taskId,list.get(0).getToNode())) {
					result.setSuccess(true);
				}else {
					result.setSuccess(false);
				}
			}else {
				result.setSuccess(false);
			}
			return result;
		}
		public Boolean getTaskTransactor(Long taskId, String taskNodeName){
			if(taskNodeName.contains("结束")) {
				return true;
			}
			List<String> claimUsers=taskService.getTaskNodeAssignees(taskId,taskNodeName);
			List<Map<String,String>> list = new ArrayList<Map<String,String>>();
			for(String t:claimUsers) {
				Map<String,String> map = new HashMap<String,String>();
				User u = userService.findByName(t);
				map.put("name", t);
				map.put("actual_name", u.getActual_name());
				list.add(map);
				//System.out.println("name="+t);
			}
			if(0<list.size() && list.size()<=1) {
				return true;
			}else {
				return false;
			}
		}
		
		//表单设计器判断当前数据是否可编辑
		@RequestMapping("dataIfUpdate")
		public ReturnBean dataIfUpdate(String tableName,String businessId,HttpSession session) {
			User u = (User) session.getAttribute("user");
			String sql = "";
			sql += " SELECT";
			sql += " 	m.*, task.assignee_,task.owner_ from "+tableName+" m ";
			sql += " inner join uflo_task task on m.uuid = task.business_id_";
			sql += " where m.uuid= '"+businessId+"'";
			Map<String,Object> map = jdbc.queryForMap(sql);
			System.out.println(u.getId()+"当前登录用户的id");
			System.out.println(map.get("create_user_id").toString()+"数据新增者id");
			System.out.println(map.get("create_user_id").equals(u.getId()));
			Integer create_user_id = Integer.valueOf((String) map.get("create_user_id"));
			if(!create_user_id.equals(u.getId())) {
				return new ReturnBean(false,"对不起您没有权限修改");
			}else if(null==map.get("assignee_")) {
				return new ReturnBean(true,"您看可以修改");
			}else if(map.get("assignee_").equals(map.get("owner_"))) {
				return new ReturnBean(true,"您看可以修改");
			}else {
				return new ReturnBean(false,"不可修改");
			}
			
		}
		
		/**
		 * 获取待办任务列表
		 * @param req
		 * @param resp
		 * @return
		 * @throws ServletException
		 * @throws IOException
		 * @author liuyu
		 */
		@GetMapping("loadTodoApp")
		public EasyUiDataGrid2 loadTodoApp(HttpServletRequest req, HttpServletResponse resp,HttpSession session) throws ServletException, IOException {
			String taskName=req.getParameter("taskName");
			String y = req.getParameter("a");
			String tName=req.getParameter("tName");
			String loginUsername = req.getParameter("name");
			String _page = req.getParameter("page");
			String _rows = req.getParameter("rows");
			int page = Integer.parseInt(_page);
			int rows = Integer.parseInt(_rows);
			int firstResult=(page-1)*rows;
			int total=0;
			//System.out.println(req.getSession().getMaxInactiveInterval()+"超期时长！！！！！！！！！！！！！！");
			List<Task> tasks = null;
			List<Map<String,String>> list = new ArrayList<Map<String,String>>();
			TaskQuery query=taskService.createTaskQuery();
			query.addTaskState(TaskState.Created);
			query.addTaskState(TaskState.InProgress);
			query.addTaskState(TaskState.Ready);
			query.addTaskState(TaskState.Suspended);
			query.addTaskState(TaskState.Reserved);
			if(!"".equals(tName)&&null!=tName) {
				Tips tip = tipsService.findByTName(tName);
				if(null!=tip) {
					query.rootProcessInstanceId(Long.valueOf(tip.getProcInsId()));
					query.addAssignee(loginUsername).addOrderDesc("createDate").page(firstResult, rows);
					if(StringUtils.isNotBlank(taskName))
						query.nameLike("%"+taskName+"%");
				}else 
					return new EasyUiDataGrid2(total, list);
				
			}else {
				query.addAssignee(loginUsername).addOrderDesc("createDate").page(firstResult, rows);
				if(StringUtils.isNotBlank(taskName))
					query.nameLike("%"+taskName+"%");
			}
			query.count();
			tasks=query.list();
			for(Task t:tasks) {
				Map<String,String> map = new HashMap<String,String>();
				//System.out.println(t.getRootProcessInstanceId());
				HistoryTaskQuery his = historyService.createHistoryTaskQuery().rootProcessInstanceId(t.getRootProcessInstanceId()).addOrderAsc("createDate");
				List<HistoryTask> h = his.list();
				Tips tp = tipsService.selectByProcInsId(String.valueOf(t.getRootProcessInstanceId()));
				if(null!=tp) 
				map.put("tips", tp.getTName());
				User user = userService.findByName(t.getAssignee());
				User crateUser = userService.findByName(h.get(0).getOwner());
				//获取节点类型
				ProcessDefinition pd = processService.getProcessById(t.getProcessId());
				map.put("firBusinessId", h.get(0).getBusinessId());
				map.put("firUrl", h.get(0).getUrl());
				map.put("taskName", t.getTaskName());
				map.put("title", pd.getName());
				map.put("id", String.valueOf(t.getId()));
				map.put("assignee", user.getActual_name());
				map.put("progress", String.valueOf(t.getProgress()));
				map.put("state", String.valueOf(t.getState()));
				map.put("own", t.getOwner());
				map.put("description", t.getDescription());
				map.put("businessId", t.getBusinessId());
				map.put("processInstanceId", String.valueOf(t.getProcessInstanceId()));
				map.put("createDate", formatDate(t.getCreateDate()));
				map.put("ulfoCreateDate", formatDate(h.get(0).getCreateDate()));//流程创建时间
				map.put("cretePerson", crateUser.getActual_name());//发起人
				map.put("prevTask", t.getPrevTask());
				map.put("url", t.getUrl());
				Node node = pd.getNode(t.getNodeName());
				List<SequenceFlowImpl> nodes=node.getSequenceFlows();
				if(nodes!=null&&nodes.size()==1){
					for(SequenceFlowImpl flow:nodes){
						String flowName=flow.getToNode();
						if(flowName!=null && !flowName.startsWith(TaskService.TEMP_FLOW_NAME_PREFIX)){
							Node n = pd.getNode(flow.getToNode());
							map.put("nodeType", n.getType().name());
							map.put("nextNode", flowName);
						}
					}
				}
				if(y != null && !y.equals("")) {
					if(pd.getName().indexOf(y) != -1) {
						list.add(map);
					}
				}else {
					list.add(map);
				}
			}
			return new EasyUiDataGrid2(total, list);
		}
}
